package com.yesido.javabase.concurrent;

/**
 * @author yesido
 * @description
 * @date 2023-06-24 22:42
 * @Version 8.3
 */
public class ThreadLocalExample {
    // 创建一个 ThreadLocal 对象
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 在主线程中设置值
        threadLocal.set("Hello, World!");

        // 创建一个新的线程并启动
        Thread thread = new Thread(() -> {
            threadLocal.set(Thread.currentThread().getName()+"===");
            // 在新线程中获取值
            String value = threadLocal.get();
            System.out.println("Value in new thread: " + value);
            threadLocal.remove();
        });
        thread.start();

        // 在主线程中获取值
        String value = threadLocal.get();
        System.out.println("Value in main thread: " + value);

        // 清除值
        threadLocal.remove();
    }
}
